package com.laolei.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@ComponentScan
public final class AsyncUtils implements ApplicationContextAware {
	static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException {
		applicationContext = _applicationContext;
	}

	private static AsyncUtils asyncUtils;

	@Async
	<T> void async(AsyncEvent<T> event, T t) {
		event.apply(t);
	}

	public static <T> void execute(AsyncEvent<T> event, T t) {
		if (asyncUtils == null)
			asyncUtils = applicationContext.getBean(AsyncUtils.class);
		asyncUtils.async(event, t);
	}

	@Async
	<T> void async(AsyncEventPart<T> event) {
		event.apply();
	}

	public static <T> void execute(AsyncEventPart<T> event) {
		if (asyncUtils == null)
			asyncUtils = applicationContext.getBean(AsyncUtils.class);
		asyncUtils.async(event);
	}

	public static interface AsyncEvent<T> {
		void apply(T t);
	}

	public static interface AsyncEventPart<T> {
		void apply();
	}
}
